package StudyCode.Component;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @author lixiaoyao
 */
public class ColorChooserFrame extends JFrame {

	public ColorChooserFrame() {
		setLayout(new FlowLayout());
		JButton buttonModel = new JButton("Model");
		buttonModel.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				Color defaultColor = getBackground();
				Color selected = JColorChooser.showDialog(ColorChooserFrame.this, "Set background", defaultColor);
				if (selected != null) {
					setBackground(selected);
				}
			}
		});
		add(buttonModel);

		JButton buttonModeless = new JButton("Modeless");
		buttonModeless.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				final JColorChooser colorChooser = new JColorChooser();
				JDialog dialog = JColorChooser.createDialog(ColorChooserFrame.this, "Background Color", false /* not model */, colorChooser, new ActionListener() {
					@Override
					public void actionPerformed(ActionEvent e) {
						setBackground(colorChooser.getColor());
					}
				}, null);
				colorChooser.setColor(getBackground());
				dialog.setVisible(true);
			}
		});

		add(buttonModeless);

		JButton buttonImmediate = new JButton("Immediate");
		buttonImmediate.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				final JColorChooser colorChooser = new JColorChooser();
				colorChooser.getSelectionModel().addChangeListener(new ChangeListener() {
					@Override
					public void stateChanged(ChangeEvent e) {
						setBackground(colorChooser.getColor());
					}
				});
				JDialog dialog = new JDialog((Frame) null, false);
				dialog.add(colorChooser);
				dialog.pack();
				colorChooser.setColor(getBackground());
				dialog.setVisible(true);
			}
		});
		add(buttonImmediate);
		RepaintManager.currentManager(getRootPane()).setDoubleBufferingEnabled(false);
		getRootPane().setDebugGraphicsOptions(DebugGraphics.FLASH_OPTION);
	}

	public static void main(String[] args) {
		ColorChooserFrame colorChooserFrame =new ColorChooserFrame();
		colorChooserFrame.setSize(400,300);
		colorChooserFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		colorChooserFrame.setVisible(true);
	}

}
